package com.heima.cn;

import com.heima.com.Student;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet("/AddServletStudent")
public class AddServletStudent extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收req的中数据
        String username = req.getParameter("username");
        String age = req.getParameter("age");
        String soccer = req.getParameter("soccer");
        //将数据进行封装到一个学生类对象中
        Student student = new Student();
        student.setName(username);
        student.setAge(Integer.parseInt(age));
        student.setSoccer(Integer.parseInt(soccer));
        System.out.println(student);
        //将学生保存到本地磁盘中
        BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\stu.txt",true));
        bw.write(student.getName()+","+student.getAge()+","+student.getSoccer());
        bw.newLine();
        bw.close();
        //通过响应流将数据输出到游览器中
        resp.setContentType("text/html;charset=UTF-8");//设置编码的时候一定要设置成text/html不然会自动下载不会响应到游览器中
        resp.getWriter().write("存储成功，2秒自动跳转页面");
        resp.setHeader("Refresh","2;URL=/requestReader/index.html");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
